import React from 'react';
import Picker from 'antd-mobile/lib/picker';
import Toast from 'antd-mobile/lib/toast';
import isSroll from 'iscroll/build/iscroll-probe';
import ProductItem from 'shared/components/ProductItem';
import getUrlParam from 'shared/utils/getUrlParam';
import { fetchCategoryfilterList, fetchProductListApi } from '../api';
import OrderbyTypeLabel from '../OrderbyTypeLabel';

export default class ProductList extends React.PureComponent {
  constructor(props){
    super(props)
    this.state = {
      listData:[],
      orderType: '综合排序',
      categoryfilterList: []
    }
    this.getList = this.getList.bind(this);
    this.page = 1;
    this.categoryId = props.categoryId;
    this.filterCategoryId = props.filterCategoryId;
    this.orderData = [{value:'',label:'综合排序'},{value:'desc',label:'价格降序'},{value:'asc',label:'价格升序'},{value:'new',label:'新品排序'}];
    this.busData = {
      category_id: this.filterCategoryId,
      orderby: '',
      sortby: '',
      page: 1,
    }
  }

  componentDidMount() {
    document.querySelector('.wrapper').addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
    this.getList(this.busData);
    this.getCategoryfilterList();
    this.scroll = new isSroll('.wrapper', {
      mouseWheel: true,
      click: true,
      tap: true,
      probeType: 2,
    });
    this.initPagination()
  }

  componentWillReceiveProps({ categoryId, filterCategoryId }) {
    if (this.busData.categoryId !== categoryId) {
      this.categoryId = categoryId;
      this.busData.category_id = filterCategoryId;
      this.setState({listData:[], showloadAllMessage: false});
      this.busData.page = 1;
      this.totalpage = 0;
      this.getList(this.busData)
      this.getCategoryfilterList();
      this.initPagination();
    }
  }

  componentWillUnmount() {
    Toast.hide()
  }

  initPagination() {
    this.scroll.on('scrollEnd', () => {
      if (this.totalpage === this.busData.page && !this.state.showloadAllMessage) {
        this.setState({ showloadAllMessage: true }, () => {
          this.scroll.refresh();
        })
        return;
      }

      if (this.scroll.y - 400 < this.scroll.maxScrollY && this.totalpage > this.busData.page) {
        this.onEndReached()
      }
    });
  }

  getList(data, pageChange){
    Toast.loading('数据加载中', 5)
    fetchProductListApi(data)
      .then(({ data }) => {
        Toast.hide();
        this.total = data.total;
        this.totalpage = data.totalpage;
        let { listData } = this.state;

        if(pageChange){
          listData = listData.concat(data.productlist);
        }else{
          listData = data.productlist;
        }
        if (listData.length < data.limit) {
          this.setState({ showloadAllMessage: true })
        }
        this.setState({ listData }, () => {
          this.scroll.refresh();
        });
      })
  }

  getCategoryfilterList() {
    fetchCategoryfilterList({ category_id: this.categoryId }).then(({ data }) => {
      const { categorylist } = data
      this.setState({ categoryfilterList: categorylist });
    })
  }

  orderCtrl = (val) => {
    const type = this.orderData.filter((item) => { return item.value == val[0] });
    gloablMonitor(['商品列表页-排序', type[0].label]);

    let sortBy = '';
    let value = '';
    if(val[0] == 'desc' || val[0] == 'asc'){
      sortBy = val[0];
      value = 'price'
    }else{
      sortBy = '';
      value = val[0]
    }
    this.busData.sortby = sortBy;
    this.busData.orderby = value;
    this.setState({orderType:type[0].label});
    this.getList(this.busData);
  }

  handleFilterCategory = (categoryId, title) => {
    gloablMonitor([`商品列表页-${title}`, title])
    this.props.history.push(`/allProduct?defaultCategoryId=${this.props.categoryId}&filterCategoryId=${categoryId}`)
    // this.filterCategoryId = '';
    // this.busData.category_id = categoryId;
    this.busData.page = 1;
    // this.getList(this.busData);
  }

  renderItem = (item, key) => {
    return (
      <ProductItem key={key} data={item} />
    );
  }

  onEndReached = () => {
    const { busData } = this;
    busData.page++;
    this.getList(busData,'pageChange');
  }

  render() {
    const { listData, orderType, categoryfilterList } = this.state;
    const id = this.props.categoryId;

    return (
      <div className="product-list">
        <div className="product-list-name">{this.props.title}</div>
        <div className="product-list-childname">
          <ul>
            <li
              className={`${this.props.filterCategoryId === id ? 'selected' : ''}`}
              data-id={id}
              onClick={()=> { this.handleFilterCategory(id, '全部') }}
            >
              全部
            </li>
            {
              categoryfilterList.map((item, index) => (
                <li
                  key={index}
                  data-id={item.category_id}
                  className={`${getUrlParam('filterCategoryId') === item.category_id ? 'selected' : ''}`}
                  onClick={() => { this.handleFilterCategory(item.category_id, item.title) }}
                >
                  {item.title}
                </li>
              ))
            }
          </ul>
        </div>
        <div className="product-list-order">
          <div className="type-show">{`${orderType}`}</div>
          <Picker data={this.orderData} cols={1} extra={`${orderType}`}  className="forss" onOk={this.orderCtrl}>
            <OrderbyTypeLabel />
          </Picker>
        </div>

        <div className="wrapper">
          <div className="scroller">
            {
              listData.map((item, index)=> <ProductItem key={index} data={item} />)
            }
            {
              this.state.showloadAllMessage &&
              <div className="product-loadall" key="all">
                <div>{listData.length ? '全部加载完毕' : '暂无商品'}</div>
              </div>
            }
          </div>
        </div>
        {/* <ListView
          height={300}
          data={listData}
          renderItem={this.renderItem}
          onEndReached={this.onEndReached}
          hasMore={listData.length < this.total}
        /> */}
      </div>
    )
  }
}